package com.hhxyjsj.framework.logging.support;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

public class LogManager {
	
	private static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
	
	/**
	 * 默认的日志目录 
	 */
	private static String DEFAULT_LOG_PATH = "/logs";
	
	/**
	 * 默认日志文件格式
	 */
	private static String DEFAULT_LOG_FILE_NAME_PREFIX = "catalina";
	
	private static String logPath;
	private static String fileNamePrefix;
	private static String currDate;
	private static OutputStream os;
	
	static{
		Properties p = new Properties();
		try {
			p.load(LogManager.class.getClassLoader().getResourceAsStream("log.properties"));
			logPath = p.getProperty("log.filePath");
			logPath = logPath.replace("//", "/");
			logPath = logPath.endsWith("/") ? logPath.substring(0, logPath.length() - 1) : logPath;
			logPath = logPath == null || "".equals(logPath) ? DEFAULT_LOG_PATH : logPath;
			
			fileNamePrefix = p.getProperty("log.fileNamePrefix");
			fileNamePrefix = fileNamePrefix == null || "".equals(fileNamePrefix) ? DEFAULT_LOG_FILE_NAME_PREFIX : fileNamePrefix;
			setOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static synchronized void setOutputStream() throws FileNotFoundException{
		File directory = new File(logPath);
		if(!directory.exists()){
			directory.mkdirs();
		}
		currDate = SDF.format(new Date());
		os = new FileOutputStream(new File(logPath + "/" + fileNamePrefix + "." + currDate + ".log"),true);
	}
	
	public static synchronized void append(String msg) throws UnsupportedEncodingException, IOException{
		String date = SDF.format(new Date());
		if(!date.equals(currDate)){
			os.close();
			setOutputStream();
		}
		os.write((msg + "\r\n").getBytes("UTF-8"));
		os.flush();
	}
}
